package com.asiainfo.dao;

import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcConnection {

	
	public static Connection getConnection() throws Exception{
		//通过配置文件读取数据库连接信息
		Properties prop = new Properties();
		FileInputStream fileStrm = new FileInputStream("config/config.properties");
		prop.load(fileStrm);
		prop.list(System.out);
		String driver = prop.getProperty("driver");
		String jdbc = prop.getProperty("jdbc");
		String user = prop.getProperty("user");
		String passwd = prop.getProperty("passwd");
		Connection connection = null;

		//加载数据库驱动器获取数据库连接
		try{
			Class.forName(driver);
		}catch (Exception e){
			e.printStackTrace();
			System.out.println("加载数据库驱动失败。");
		}
		
		try{
			connection = (Connection) DriverManager.getConnection(jdbc, user, passwd);
		}catch(SQLException e){
			e.printStackTrace();
			System.out.println("初始化数据库连接失败");
		}
		
		return connection;
	}

	public static void closeConnection(PreparedStatement pstmt, ResultSet resultSet, Connection connection){
		//关闭PreparedStatement
		if (pstmt != null){
			try{
				pstmt.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}

		//关闭ResultSet
		if (resultSet != null){
			try{
				resultSet.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}

		//关闭connection
		if (connection != null){
			try{
				connection.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
	}
}
